@loopback/context
This module provides facilities to manage artifacts and their dependencies using
Context
in your Node.js applications. It can be used independent of the
LoopBack framework.
Overview
The @loopback/context
package exposes TypeScript/JavaScript APIs and
decorators to register artifacts, declare dependencies, and resolve artifacts
by keys. The Context
also serves as an IoC container to support dependency injection.
Context
and Binding
are the two core concepts. A context is a registry of
bindings and each binding represents a resolvable artifact by the key.
- Bindings can be fulfilled by a constant, a factory function, a class, or a
provider.
- Bindings can be grouped by tags and searched by tags.
- Binding scopes can be used to control how a resolved binding value is shared.
- Bindings can be resolved synchronously or asynchronously.
- Provide
@inject
and other variants of decorators to express dependencies. - Support Constructor, property, and method injections.
- Allow contexts to form a hierarchy to share or override bindings.
- Track bindings and injections during resolution to detect circular dependencies.
Installation
$ npm install --save @loopback/context
Basic use
Locate an artifact by key
const Context = require('@loopback/context').Context;
const ctx = new Context();
ctx.bind('hello').to('world');
const helloVal = ctx.getSync('hello');
console.log(helloVal);
The binding can also be located asynchronously:
const helloVal = await ctx.get('hello');
console.log(helloVal);
Dependency injection using context
import {Context, inject} from '@loopback/context';
const ctx = new Context();
ctx.bind('greeting').to('Hello');
class HelloController {
constructor(
@inject('greeting') private greeting: string) {
}
greet(name) {
return `${this.greeting}, ${name}`;
}
}
ctx.bind('HelloController').toClass(HelloController);
async function hello() {
const helloController: HelloController = await ctx.get('HelloController');
console.log(helloController.greet('John'));
}
hello();
For additional information, please refer to the Context page.
Contributions
IBM/StrongLoop is an active supporter of open source and welcomes contributions to our projects as well as those of the Node.js community in general. For more information on how to contribute please refer to the Contribution Guide.
Tests
Run npm test
from the root folder.
Contributors
See all contributors.
License
MIT